/*
 * @Author: wuqingchun
 * @Date: 2024-06-24 14:49:11
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-06-24 15:27:35
 */

// gcc -O2 -o app_optimize_barrier app_optimize_barrier.cpp
// objdump -S 
/*
0000000000000610 <_Z24func_no_optimize_barrierv>:
 610:   8b 05 fe 09 20 00       mov    0x2009fe(%rip),%eax        # 201014 <g_iR>
 616:   c7 05 f8 09 20 00 01    movl   $0x1,0x2009f8(%rip)        # 201018 <g_iY>
 61d:   00 00 00 
 620:   89 05 f6 09 20 00       mov    %eax,0x2009f6(%rip)        # 20101c <g_iX>
 626:   c3                      retq   
 627:   66 0f 1f 84 00 00 00    nopw   0x0(%rax,%rax,1)
 62e:   00 00 

0000000000000630 <_Z21func_optimize_barrierv>:
 630:   8b 05 de 09 20 00       mov    0x2009de(%rip),%eax        # 201014 <g_iR>
 636:   89 05 e0 09 20 00       mov    %eax,0x2009e0(%rip)        # 20101c <g_iX>
 63c:   c7 05 d2 09 20 00 01    movl   $0x1,0x2009d2(%rip)        # 201018 <g_iY>
 643:   00 00 00 
 646:   c3                      retq   
 647:   66 0f 1f 84 00 00 00    nopw   0x0(%rax,%rax,1)
 64e:   00 00 

0000000000000650 <_Z16func_access_oncev>:
 650:   8b 05 be 09 20 00       mov    0x2009be(%rip),%eax        # 201014 <g_iR>
 656:   89 05 c0 09 20 00       mov    %eax,0x2009c0(%rip)        # 20101c <g_iX>
 65c:   c7 05 b2 09 20 00 01    movl   $0x1,0x2009b2(%rip)        # 201018 <g_iY>
 663:   00 00 00 
 666:   c3                      retq   
 667:   66 0f 1f 84 00 00 00    nopw   0x0(%rax,%rax,1)
 66e:   00 00 
*/

int g_iX, g_iY, g_iR;

#define barrier() __asm__ volatile ("":::"memory")

#define ACCESS_ONCE(x) (*(volatile typeof(x) *)&(x))


void func_no_optimize_barrier()
{
    g_iX = g_iR;
    g_iY = 1;
}

void func_optimize_barrier()
{
    g_iX = g_iR;
    barrier();
    g_iY = 1;
}

void func_access_once()
{
    ACCESS_ONCE(g_iX) = g_iR;
    ACCESS_ONCE(g_iY) = 1;
}

int main(int argc, char** argv)
{
    return 0;
}